package com.caseprocessing.service;

import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * 法条引用验证器
 * 验证法律条文引用的格式和完整性
 */
public class LegalCitationValidator {
    
    // 法律法规引用格式模式
    private static final Pattern LAW_CITATION_PATTERN = 
        Pattern.compile("《([^》]+)》\\s*第([\\d]+)条(?:第([\\d]+)款)?(?:第([\\d]+)项)?");
    
    // 完整法条引用模式（包含具体条文内容）
    private static final Pattern DETAILED_CITATION_PATTERN = 
        Pattern.compile("根据《([^》]+)》第([\\d]+)条[^，。]*的规定");
    
    // 常见法律法规数据库
    private static final Map<String, LawInfo> LAW_DATABASE = new HashMap<>();
    
    static {
        initializeLawDatabase();
    }
    
    /**
     * 验证法条引用
     */
    public LegalCitationResult validateLegalCitations(String content) {
        LegalCitationResult result = new LegalCitationResult();
        List<String> issues = new ArrayList<>();
        List<CitationInfo> citations = extractCitations(content);
        
        if (citations.isEmpty()) {
            issues.add("未发现法律依据引用");
            result.setValid(false);
        } else {
            // 验证每个引用
            for (CitationInfo citation : citations) {
                validateSingleCitation(citation, issues);
            }
            result.setValid(issues.isEmpty());
        }
        
        result.setIssues(issues);
        result.setCitations(citations);
        
        return result;
    }
    
    /**
     * 提取法条引用信息
     */
    private List<CitationInfo> extractCitations(String content) {
        List<CitationInfo> citations = new ArrayList<>();
        Matcher matcher = LAW_CITATION_PATTERN.matcher(content);
        
        while (matcher.find()) {
            CitationInfo citation = new CitationInfo();
            citation.setLawName(matcher.group(1));
            citation.setArticle(Integer.parseInt(matcher.group(2)));
            
            if (matcher.group(3) != null) {
                citation.setParagraph(Integer.parseInt(matcher.group(3)));
            }
            
            if (matcher.group(4) != null) {
                citation.setItem(Integer.parseInt(matcher.group(4)));
            }
            
            citation.setFullText(matcher.group(0));
            citations.add(citation);
        }
        
        return citations;
    }
    
    /**
     * 验证单个法条引用
     */
    private void validateSingleCitation(CitationInfo citation, List<String> issues) {
        // 1. 法律名称格式检查
        validateLawNameFormat(citation, issues);
        
        // 2. 法律存在性检查
        validateLawExistence(citation, issues);
        
        // 3. 条文编号合理性检查
        validateArticleNumber(citation, issues);
        
        // 4. 引用完整性检查
        validateCitationCompleteness(citation, issues);
    }
    
    /**
     * 验证法律名称格式
     */
    private void validateLawNameFormat(CitationInfo citation, List<String> issues) {
        String lawName = citation.getLawName();
        
        // 检查是否为完整的法律名称
        if (!lawName.endsWith("法") && !lawName.endsWith("条例") && 
            !lawName.endsWith("规定") && !lawName.endsWith("办法")) {
            issues.add("法律名称格式可能不完整：" + lawName);
        }
        
        // 检查是否包含发布机关（对于行政法规）
        if (lawName.contains("条例") || lawName.contains("规定")) {
            if (!lawName.contains("国务院") && !lawName.contains("中华人民共和国")) {
                // 可能需要补充发布机关信息（警告级别）
            }
        }
    }
    
    /**
     * 验证法律存在性
     */
    private void validateLawExistence(CitationInfo citation, List<String> issues) {
        String lawName = citation.getLawName();
        LawInfo lawInfo = LAW_DATABASE.get(lawName);
        
        if (lawInfo == null) {
            // 尝试模糊匹配
            lawInfo = findSimilarLaw(lawName);
            if (lawInfo != null) {
                issues.add("法律名称可能有误，建议核实：" + lawName + "（是否为：" + lawInfo.getFullName() + "）");
            } else {
                issues.add("未在法律数据库中找到：" + lawName + "，请核实法律名称");
            }
        } else {
            citation.setLawInfo(lawInfo);
        }
    }
    
    /**
     * 验证条文编号
     */
    private void validateArticleNumber(CitationInfo citation, List<String> issues) {
        LawInfo lawInfo = citation.getLawInfo();
        if (lawInfo == null) return;
        
        int article = citation.getArticle();
        
        // 检查条文编号是否在合理范围内
        if (article <= 0) {
            issues.add("条文编号无效：第" + article + "条");
        } else if (lawInfo.getTotalArticles() > 0 && article > lawInfo.getTotalArticles()) {
            issues.add("条文编号超出范围：《" + citation.getLawName() + "》第" + article + "条（该法律共" + lawInfo.getTotalArticles() + "条）");
        }
        
        // 检查款项编号
        if (citation.getParagraph() != null && citation.getParagraph() <= 0) {
            issues.add("款项编号无效：第" + citation.getParagraph() + "款");
        }
        
        if (citation.getItem() != null && citation.getItem() <= 0) {
            issues.add("项目编号无效：第" + citation.getItem() + "项");
        }
    }
    
    /**
     * 验证引用完整性
     */
    private void validateCitationCompleteness(CitationInfo citation, List<String> issues) {
        // 检查是否应该包含具体条文内容
        if (citation.getLawName().contains("行政处罚法")) {
            // 行政处罚法的关键条文应该有具体说明
            if (isKeyArticle(citation.getArticle()) && !citation.getFullText().contains("规定")) {
                issues.add("重要法条建议包含具体条文内容：《" + citation.getLawName() + "》第" + citation.getArticle() + "条");
            }
        }
    }
    
    /**
     * 查找相似法律
     */
    private LawInfo findSimilarLaw(String lawName) {
        for (Map.Entry<String, LawInfo> entry : LAW_DATABASE.entrySet()) {
            String storedName = entry.getKey();
            LawInfo lawInfo = entry.getValue();
            
            // 简单的相似度匹配
            if (calculateSimilarity(lawName, storedName) > 0.8 || 
                calculateSimilarity(lawName, lawInfo.getShortName()) > 0.8) {
                return lawInfo;
            }
        }
        return null;
    }
    
    /**
     * 计算字符串相似度（简化版本）
     */
    private double calculateSimilarity(String s1, String s2) {
        int maxLength = Math.max(s1.length(), s2.length());
        if (maxLength == 0) return 1.0;
        
        int commonLength = 0;
        int minLength = Math.min(s1.length(), s2.length());
        
        for (int i = 0; i < minLength; i++) {
            if (s1.charAt(i) == s2.charAt(i)) {
                commonLength++;
            }
        }
        
        return (double) commonLength / maxLength;
    }
    
    /**
     * 判断是否为关键条文
     */
    private boolean isKeyArticle(int article) {
        // 行政处罚法中的关键条文
        int[] keyArticles = {4, 5, 6, 12, 13, 14, 15, 23, 31, 42, 44, 51};
        for (int key : keyArticles) {
            if (article == key) return true;
        }
        return false;
    }
    
    /**
     * 初始化法律数据库
     */
    private static void initializeLawDatabase() {
        // 行政处罚法
        LAW_DATABASE.put("中华人民共和国行政处罚法", 
            new LawInfo("中华人民共和国行政处罚法", "行政处罚法", 83, "2021年修订"));
        
        // 行政许可法
        LAW_DATABASE.put("中华人民共和国行政许可法", 
            new LawInfo("中华人民共和国行政许可法", "行政许可法", 83, "2019年修订"));
        
        // 行政强制法
        LAW_DATABASE.put("中华人民共和国行政强制法", 
            new LawInfo("中华人民共和国行政强制法", "行政强制法", 71, "2011年"));
        
        // 食品安全法
        LAW_DATABASE.put("中华人民共和国食品安全法", 
            new LawInfo("中华人民共和国食品安全法", "食品安全法", 154, "2018年修订"));
        
        // 环境保护法
        LAW_DATABASE.put("中华人民共和国环境保护法", 
            new LawInfo("中华人民共和国环境保护法", "环境保护法", 70, "2014年修订"));
        
        // 可以继续添加更多法律法规...
    }
    
    /**
     * 法条引用验证结果
     */
    public static class LegalCitationResult {
        private boolean valid;
        private List<String> issues;
        private List<CitationInfo> citations;
        
        public LegalCitationResult() {
            this.issues = new ArrayList<>();
            this.citations = new ArrayList<>();
        }
        
        public boolean isValid() { return valid; }
        public void setValid(boolean valid) { this.valid = valid; }
        
        public List<String> getIssues() { return issues; }
        public void setIssues(List<String> issues) { this.issues = issues; }
        
        public List<CitationInfo> getCitations() { return citations; }
        public void setCitations(List<CitationInfo> citations) { this.citations = citations; }
    }
    
    /**
     * 法条引用信息
     */
    public static class CitationInfo {
        private String lawName;
        private int article;
        private Integer paragraph;
        private Integer item;
        private String fullText;
        private LawInfo lawInfo;
        
        public String getLawName() { return lawName; }
        public void setLawName(String lawName) { this.lawName = lawName; }
        
        public int getArticle() { return article; }
        public void setArticle(int article) { this.article = article; }
        
        public Integer getParagraph() { return paragraph; }
        public void setParagraph(Integer paragraph) { this.paragraph = paragraph; }
        
        public Integer getItem() { return item; }
        public void setItem(Integer item) { this.item = item; }
        
        public String getFullText() { return fullText; }
        public void setFullText(String fullText) { this.fullText = fullText; }
        
        public LawInfo getLawInfo() { return lawInfo; }
        public void setLawInfo(LawInfo lawInfo) { this.lawInfo = lawInfo; }
        
        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("《").append(lawName).append("》第").append(article).append("条");
            if (paragraph != null) sb.append("第").append(paragraph).append("款");
            if (item != null) sb.append("第").append(item).append("项");
            return sb.toString();
        }
    }
    
    /**
     * 法律信息
     */
    public static class LawInfo {
        private String fullName;
        private String shortName;
        private int totalArticles;
        private String version;
        
        public LawInfo(String fullName, String shortName, int totalArticles, String version) {
            this.fullName = fullName;
            this.shortName = shortName;
            this.totalArticles = totalArticles;
            this.version = version;
        }
        
        public String getFullName() { return fullName; }
        public String getShortName() { return shortName; }
        public int getTotalArticles() { return totalArticles; }
        public String getVersion() { return version; }
    }
}